#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

int create_server()
{
	struct addrinfo hints, *res = NULL;
	memset(&hints, 0, sizeof(hints));
	hints.ai_family = AF_INET6;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV | AI_V4MAPPED;
	int ret = getaddrinfo(NULL, "8888", &hints, &res);
	if (ret) {
		perror(gai_strerror(ret));
		exit(0);
	}

	for (struct addrinfo *pa = res; pa; pa = pa->ai_next) {
		int fd = socket(pa->ai_family, pa->ai_socktype, pa->ai_protocol);
		if (fd < 0) {
			perror("socket");
			continue;
		}
		if (bind(fd, pa->ai_addr, pa->ai_addrlen) < 0) {
			perror("bind");
			close(fd);
			continue;
		}

		int op = 1;
		if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &op, sizeof(op)) < 0) {
			perror("setsockopt");
			close(fd);
			continue;
		}
		listen(fd, 5);
		freeaddrinfo(res);
		return fd;
	}
	perror("no addr");
	exit(0);
	return 0;
}

int main()
{
	char buf[1024];
	int fd = create_server();
	char data[] = "Hello World";
	for (;;) {
		int cfd = accept(fd, NULL, 0);
		write(cfd, data, sizeof(data));
		close(cfd);
	}
	return 0;
}